package cn.com.ddapp.ddm.ui.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.adapter.OrderDetailAdpter;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.ActivityManager;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.Entity;
import cn.com.ddapp.ddm.bean.order.Detail;
import cn.com.ddapp.ddm.bean.order.OrderDetail;
import cn.com.ddapp.ddm.bean.order.OrderDetailEntity;
import cn.com.ddapp.ddm.bean.order.OrderExt;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.LogisticsActivity;
import cn.com.ddapp.ddm.ui.dialog.CommonDialog;
import cn.com.ddapp.ddm.ui.dialog.DialogHelper;
import cn.com.ddapp.ddm.ui.dialog.SmileFaceDialog;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TLog;

/**
 * Created by caopenghui on 2016-08-10.
 */
public class OrderDetailActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.listview)
    ListView listview;

    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;

    @BindView(R.id.orderNum)
    TextView mOrderNum;
    @BindView(R.id.state_image)
    ImageView mStateImage;
    @BindView(R.id.name)
    TextView mName;
    @BindView(R.id.tel)
    TextView mTel;
    @BindView(R.id.address)
    TextView mAddress;

    @BindView(R.id.shopName)
    TextView mShopName;
    @BindView(R.id.orderPrice)
    TextView mOrderPrice;
    @BindView(R.id.orderTime)
    TextView mOrderTime;
    @BindView(R.id.action1)
    TextView action1;
    @BindView(R.id.action2)
    TextView action2;
    @BindView(R.id.accepterLine)
    View mAccepterLine;
    @BindView(R.id.accepter)
    LinearLayout mAccepter;

    private List<OrderDetail> mLists = new ArrayList<>();
    private OrderDetailAdpter adaper;
    private Integer state;
    private OrderDetailEntity entity;

    @Override
    public void initView() {
        title.setText(BaseApplication.getIntstance().getResources().getString(R.string.order_detail));
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        action1.setOnClickListener(this);
        action2.setOnClickListener(this);
    }

    @Override
    public void initData() {
        requestData();
    }

    private void requestData() {
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        String userId = SPUtils.getStringData(this, SPUtils.USERID);

        final OkUtilCallback okUtilCallback =  new OkUtilCallback(mEmptyLayout) {
            @Override
            public void onMyResponse(String response, int id) {
                TLog.log(getActivityTag(),response);
                entity = gson.fromJson(response,OrderDetailEntity.class);
                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))&&entity.getLogin()){
                    mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                }else if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                }else{
                    Detail detail = entity.getDetail();
                    mOrderNum.setText(detail.getOrder().getOrderNo());
                    OrderExt orderExt = detail.getOrderExt();
                    if(orderExt!=null){
                        mName.setText(orderExt.getAcceptName());
                        mTel.setText(orderExt.getAcceptPhone());
                        mAddress.setText(orderExt.getAcceptAddress());
                        mAccepter.setVisibility(View.VISIBLE);
                        mAccepterLine.setVisibility(View.VISIBLE);
                    }


                   List<OrderDetail> lists =  detail.getDetailList();
                    for(OrderDetail orderDetail : lists){
                        orderDetail.setOrderStatus(detail.getOrder().getStatus());
                    }
                    mShopName.setText(entity.getwName());
                    mOrderPrice.setText(detail.getOrder().getJiaoyiAmount()+"");
                    mOrderTime.setText(entity.getCreateTimeStr());
                    state = detail.getOrder().getStatus();

                    if(1==state){
                        mStateImage.setImageResource(R.drawable.pending_payment);
                        action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.to_pay));
                        action1.setVisibility(View.VISIBLE);
                        action2.setText(BaseApplication.getIntstance().getResources().getString(R.string.action9));
                        action2.setVisibility(View.VISIBLE);
                    }else if(2==state){
                        mStateImage.setImageResource(R.drawable.o_be_shipped);
                        action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.action3));
                        action1.setVisibility(View.VISIBLE);
                    }else if(3==state){
                        mStateImage.setImageResource(R.drawable.already_shipped);
                        action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.action6));
                        action1.setVisibility(View.VISIBLE);
                        action2.setText(BaseApplication.getIntstance().getResources().getString(R.string.action5));
                        action2.setVisibility(View.VISIBLE);
                    }else if(4==state){
                        action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.action5));
                        action2.setText(BaseApplication.getIntstance().getResources().getString(R.string.action9));
                        action1.setVisibility(View.VISIBLE);
                        action2.setVisibility(View.VISIBLE);
                        mStateImage.setImageResource(R.drawable.endding);
                    }else if(state==9){
                        mStateImage.setImageResource(R.drawable.already_closed);
                        action1.setText(BaseApplication.getIntstance().getResources().getString(R.string.action9));
                        action1.setVisibility(View.VISIBLE);
                    }else{
                        mStateImage.setImageResource(R.drawable.after_sale);
                    }

                    adaper = new OrderDetailAdpter(lists,OrderDetailActivity.this);
                    listview.setAdapter(adaper);
                    mLists.addAll(lists);
                }
            }
        };
        OKUtilAPI.post(OKUtilAPI.order_detail, "userId=" + userId+"&id="+getIntent().getIntExtra("orderId",0), okUtilCallback);
    }

    @Override
    public int getContentViewId() {
        return R.layout.order_detail_activity;
    }

    @Override
    protected String getFragmentTag() {
        return OrderDetailActivity.class.getSimpleName();
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==back.getId()){
            ActivityManager.getInstance().finishActivity();
        }else  if(view.getId()==action1.getId()){
            if(state==1){
                Intent intent = new Intent(OrderDetailActivity.this,PayActivity.class);
                intent.putExtra("orderNo",entity.getDetail().getOrder().getOrderNo());
                intent.putExtra("goodsName",entity.getDetail().getDetailList().get(0).getGoodsName());
                startActivity(intent);
                finish();
            }else if(state==2){
                remindOrder(entity.getDetail().getOrder().getId());
            }else if(state==3){
                comfirmOrder(entity.getDetail().getOrder().getId());
            }else if(state==4){
                LogisticsActivity.startIntent(mContext,entity.getDetail().getOrder().getLogisticsCode(),entity.getDetail().getOrderExt().getOrderNo(),entity.getCreateTimeStr());
            }else if(state==9){
                cancelOrder(entity.getDetail().getOrder().getId());
            }

        }else  if(view.getId()==action2.getId()){
            if(state==1||state==4){
                cancelOrder(entity.getDetail().getOrder().getId());
            }
            if(state==3){
                LogisticsActivity.startIntent(mContext,entity.getDetail().getOrder().getLogisticsCode(),entity.getDetail().getOrderExt().getOrderNo(),entity.getCreateTimeStr());
            }
        }
    }

    //查看物流
    private void logistics(Integer orderId) {

    }


    /**
     * 提醒发货
     * @param orderId
     */
    private void remindOrder(Integer orderId) {
        final OkUtilCallback okUtilCallback = new OkUtilCallback(){
            @Override
            public void onMyResponse(String response, int id) {
                TLog.log("orderAdapter",response);
                Entity entity = gson.fromJson(response,Entity.class);
                if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                    SmileFaceDialog dialog =  DialogHelper.getPinterestSmileDialogCancelable(OrderDetailActivity.this);
                    dialog.show();
                }
            }
        };
        OKUtilAPI.post(OKUtilAPI.order_tips, "userId="+ SPUtils.getStringData(OrderDetailActivity.this, SPUtils.USERID)+"&orderId="+orderId, okUtilCallback);
    }

    /**
     * 取消订单
     * @param orderId
     */
    private void cancelOrder(final Integer orderId) {

        final CommonDialog dialog = DialogHelper
                .getPinterestDialogCancelable(OrderDetailActivity.this);
        dialog.setTitle(BaseApplication.getIntstance().getResources().getString(R.string.careing));
        dialog.setNegativeButton(BaseApplication.getIntstance().getResources().getString(R.string.cancel), null);
        dialog.setPositiveButton(BaseApplication.getIntstance().getResources().getString(R.string.OK),new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                (OrderDetailActivity.this).showWaitDialog(BaseApplication.getIntstance().getString(R.string.order_cancel));
                String userId =  SPUtils.getStringData(OrderDetailActivity.this, SPUtils.USERID);
                final OkUtilCallback okUtilCallback = new OkUtilCallback(){
                    @Override
                    public void onMyResponse(String response, int id) {
                        (OrderDetailActivity.this).hideWaitDialog();
                        TLog.log("orderDetailAdapter",response);
                        Entity entity = gson.fromJson(response,Entity.class);
                        if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                            BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                        }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                            ActivityManager.getInstance().finishActivity();
                        }
                    }
                };
                OKUtilAPI.post(OKUtilAPI.orderCancel, "userId=" + userId+"&id="+orderId, okUtilCallback);
            }
        });
        dialog.show();
    }


    /**
     * 确认收货
     * @param orderId
     */
    private void comfirmOrder(final Integer orderId){

        final CommonDialog dialog = DialogHelper
                .getPinterestDialogCancelable(OrderDetailActivity.this);
        dialog.setTitle("是否确认收货？");
        dialog.setNegativeButton(BaseApplication.getIntstance().getResources().getString(R.string.cancel), null);
        dialog.setPositiveButton(BaseApplication.getIntstance().getResources().getString(R.string.OK),new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                OrderDetailActivity.this.showWaitDialog(BaseApplication.getIntstance().getString(R.string.order_accept));
                final OkUtilCallback okUtilCallback = new OkUtilCallback(){
                    @Override
                    public void onMyResponse(String response, int id) {
                        OrderDetailActivity.this.hideWaitDialog();
                        TLog.log("orderAdapter",response);
                        Entity entity = gson.fromJson(response,Entity.class);
                        if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                            BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.CENTER);
                        }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                            BaseApplication.showToast(R.string.confirm_order);
                            finish();
                        }
                    }
                };
                OKUtilAPI.post(OKUtilAPI.orderAccept, "userId=" + SPUtils.getStringData(OrderDetailActivity.this, SPUtils.USERID)+"&id="+orderId, okUtilCallback);
            }
        });
        dialog.show();

    }


    private String getActivityTag(){
        return OrderEvalActivity.class.getSimpleName();
    }
}
